import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,json
from common.helper import Helper
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "“顺意e生”百万医疗保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 一般医疗保险金
                "money": ["6000000"],
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 一般医疗保险金
                "money": ["4000000"],
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 一般医疗保险金
                "money": ["2000000"],
            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["expire"], plan[k]["payType"],
                             plan[k]["money"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None):
        if dt["money"] == "6000000":
            package = "P122903-T1"
        elif dt["money"] == "4000000":
            package = "P122903-T2"
        else:
            package = "P122903-T3"
        data = {"quoteList": [{"insureId": "1", "quoteReq": {"productCode": "P122903", "packageCode": package,
                                                             "channelCode": "micro", "discountKey": "", "priceFactor": [
                {"itemType": "insured", "itemFieldCode": "age", "itemFieldValue": dt["year"]},
                {"itemType": "insured_field", "itemFieldCode": "shebao", "itemFieldValue": "1" if dt["socialSec"]=="Y" else "0"}]}}]}

        payload = json.dumps( data )
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and r.json()["errCode"]==0:
            price = Helper.decimalParse( r.json()["data"]["actualPremiumAmt"]/100 )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格失败:%d*/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
